package com.gz.moreaseManager.config;

import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class SelfAccessDecisionManager implements AccessDecisionManager {

	/**
	 * 用户访问URL权限判断
	 *
	 * @param authentication   UserDetails.authorities
	 * @param object           客户端发起的requset信息
	 * @param configAttributes 拥有访问URL的角色
	 */
	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
		if (null == configAttributes || configAttributes.size() <= 0) {
			return;
		}
		String needRole;
		for (ConfigAttribute configAttribute : configAttributes) { // 循环判断权限
			needRole = configAttribute.getAttribute();
			for (GrantedAuthority authority : authentication.getAuthorities()) {
				//超级管理员拥有所有权限
				if("超级管理员".equals(authority.getAuthority())) return;
				if (needRole.trim().equals(authority.getAuthority())) {
					return;
				}
			}
		}
		throw new AccessDeniedException("没有访问权限！");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}